import axios from "axios";
import {useRouter} from "vue-router";
import {message} from "ant-design-vue";
import Cookie from "js-cookie";

const token = Cookie.get("token");
// 地址
const instance = axios.create({
    baseURL: "/api/back"
});
// 图片上传地址
export const BASE_UPLOAD_FILE = "/api/common/upload"
//请求拦截器
instance.interceptors.request.use(async (config) => {
    // 是否为登录请求
    if ((config.url ?? '').indexOf('login') < 0) {
        // 添加token
        if (token) {
            config.headers['token'] = token;
        } else {
            await message.info('未登录授权');
            setTimeout(() => {
                window.location.href = "/";
            }, 1000)
        }
    }
    return config
});

// 响应拦截器
instance.interceptors.response.use(async (response) => {
    const {code, msg} = response.data.data;
    if (code > 201) {
        await Promise.reject(msg)
    }
    return response;
}, async (err) => {
    const {code, msg} = err.response.data.data;
    if (code > 201) {
        await Promise.reject(msg)
    }
});

export default instance